package frame;

import bean.Feriado;
import controle.CalcHora;
import dao.FeriadoDAO;
import java.awt.Font;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

public class FeriadosFrame extends javax.swing.JFrame {

    List<Feriado> lista;
    SimpleDateFormat data = new SimpleDateFormat("dd/MM/yyyy");
    Date data_jdate = null;
    int selectedRow = 0;
    String tipo_pesq;
    String str_pesq;
            
 
    public FeriadosFrame() {
        initComponents();
        jDateChooser_data.setDate(new java.util.Date());      
        preencher_jtable(tipo_pesq, str_pesq);
         }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenu1 = new javax.swing.JMenu();
        jLabeldata = new javax.swing.JLabel();
        jTextField_descricao = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jButton_gravar = new javax.swing.JButton();
        jButton_limpar = new javax.swing.JButton();
        jButton_deletar = new javax.swing.JButton();
        jButton_pesquisar = new javax.swing.JButton();
        jDateChooser_data = new com.toedter.calendar.JDateChooser();
        jMenuBar1 = new javax.swing.JMenuBar();

        jMenu1.setText("jMenu1");

        setTitle("Time Sheet PJ");
        setResizable(false);
        getContentPane().setLayout(null);

        jLabeldata.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jLabeldata.setText("      DATA");
        getContentPane().add(jLabeldata);
        jLabeldata.setBounds(30, 50, 80, 13);

        jTextField_descricao.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jTextField_descricao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField_descricaoActionPerformed(evt);
            }
        });
        getContentPane().add(jTextField_descricao);
        jTextField_descricao.setBounds(240, 60, 190, 18);

        jTextField2.setEditable(false);
        jTextField2.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jTextField2.setText("       DESCRIÇÃO");
        jTextField2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        getContentPane().add(jTextField2);
        jTextField2.setBounds(130, 60, 100, 17);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "id", "DATA", "DESCRICAO"
            }
        ));
        jTable1.setGridColor(new java.awt.Color(255, 255, 255));
        jTable1.setShowHorizontalLines(false);
        jTable1.setShowVerticalLines(false);
        jTable1.getTableHeader().setResizingAllowed(false);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(10, 120, 420, 130);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("CADASTRO DE FERIADOS");
        jLabel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        getContentPane().add(jLabel1);
        jLabel1.setBounds(70, 10, 300, 30);

        jPanel1.setLayout(new java.awt.GridLayout(1, 0));

        jButton_gravar.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jButton_gravar.setText("GRAVAR");
        jButton_gravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_gravarActionPerformed(evt);
            }
        });
        jPanel1.add(jButton_gravar);

        jButton_limpar.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jButton_limpar.setText("LIMPAR");
        jButton_limpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_limparActionPerformed(evt);
            }
        });
        jPanel1.add(jButton_limpar);

        jButton_deletar.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jButton_deletar.setText("DELETAR");
        jButton_deletar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_deletarActionPerformed(evt);
            }
        });
        jPanel1.add(jButton_deletar);

        jButton_pesquisar.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jButton_pesquisar.setText("PESQUISAR");
        jButton_pesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_pesquisarActionPerformed(evt);
            }
        });
        jPanel1.add(jButton_pesquisar);

        getContentPane().add(jPanel1);
        jPanel1.setBounds(10, 90, 420, 20);

        jDateChooser_data.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        getContentPane().add(jDateChooser_data);
        jDateChooser_data.setBounds(10, 60, 110, 20);
        setJMenuBar(jMenuBar1);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-447)/2, (screenSize.height-290)/2, 447, 290);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_gravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_gravarActionPerformed
        FeriadoDAO dao_save = new FeriadoDAO();
        FeriadoDAO dao_edit = new FeriadoDAO();
        FeriadoDAO dao_saveOrEdit = new FeriadoDAO();
        Feriado feriado2 = new Feriado();

        int linha = jTable1.getSelectedRow();

        if (jDateChooser_data.getDate() == null) {
            JOptionPane.showMessageDialog(null, "Data Inválida !");
        
        } else if (jTextField_descricao.getText().length() > 255) {
            JOptionPane.showMessageDialog(null, "Tam max descrição = 255 !");
       
        } else if (jTextField_descricao.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "Campo descriçao obrigatório !");
        }
        else if( duplicado() && linha >=0 ){
            JOptionPane.showMessageDialog(null, "Registro sem alterações !");
        }        
         else{
            
            if ( linha >=0 && jTable1.getValueAt(linha, 0)  != null ) 
                feriado2.setId(new Integer(jTable1.getValueAt(linha, 0).toString().trim()));
            else
                feriado2.setId(-1);
                       
            java.sql.Date data_t = new java.sql.Date(jDateChooser_data.getDate().getTime());  
            
            feriado2.setData( data_t );
            feriado2.setDescricao(jTextField_descricao.getText().trim());
                                  
            String mensagem = "" ;
                            
            if ( feriado2.getId() != -1 )
                mensagem = "Confirma a alteração do registro !";
            else
                mensagem = "Confirma a gravação do registro !";
            
            int opcao_editar = JOptionPane.showConfirmDialog(null, mensagem, "Confirmação", JOptionPane.YES_NO_OPTION);
            
            if ( feriado2.getId() != -1 && opcao_editar == JOptionPane.YES_OPTION ){
                dao_edit.editar(feriado2);
            }
            else if ( feriado2.getId() == -1 && opcao_editar == JOptionPane.YES_OPTION ){
                dao_save.salvar(feriado2);
            }
            
            jTextField_descricao.setText("");
            preencher_jtable(tipo_pesq, "");

        }
    }//GEN-LAST:event_jButton_gravarActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked

        int linhasum = jTable1.getRowCount();
        int linha = jTable1.getSelectedRow();

        
        if (linhasum >= 1 ) {

            try {
                jDateChooser_data.setDate(data.parse(jTable1.getValueAt(linha, 1).toString()));
                jTextField_descricao.setText(jTable1.getValueAt(linha, 2).toString());
               
            } catch (ParseException ex) {
                Logger.getLogger(FeriadosFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void jButton_deletarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_deletarActionPerformed

        int linha = jTable1.getSelectedRow();
        int linhasum = jTable1.getRowCount();

        FeriadoDAO dao_del = new FeriadoDAO();
        Feriado feriado_del = new Feriado();
        
        if (linhasum > 0) {
            try {
                System.out.println(jTable1.getValueAt(linha, 0).toString());
                int id = new Integer(jTable1.getValueAt(linha, 0).toString());
                String excluir = "Confirma a exclusão do registro !";
                int opcao_escolhida = JOptionPane.showConfirmDialog(null, excluir, "exclusão", JOptionPane.YES_NO_OPTION);
                if (opcao_escolhida == JOptionPane.YES_OPTION) {
                    feriado_del.setId(new Integer(id));
                    dao_del.deletar(feriado_del);
                    preencher_jtable(tipo_pesq, str_pesq);
                }
                jDateChooser_data.setDate(new java.util.Date());
                jTextField_descricao.setText("");
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Selecione um registro para excluir !");
            }
        }

    }//GEN-LAST:event_jButton_deletarActionPerformed

    private void jButton_pesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_pesquisarActionPerformed

        try
        {
            String pesq_desc = JOptionPane.showInputDialog(null, "Digite a descrição !");

            if ( pesq_desc != null )
            {
                preencher_jtable("descricao", pesq_desc);
                jDateChooser_data.setDate(new java.util.Date());
                jTextField_descricao.setText("");             
            }             
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(null, "Erro ao Pesquisar !" + e);   
        }

    }//GEN-LAST:event_jButton_pesquisarActionPerformed

    private void jButton_limparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_limparActionPerformed

        jDateChooser_data.setDate(new java.util.Date());
        jTextField_descricao.setText("");
        preencher_jtable(tipo_pesq, str_pesq);
       
    }//GEN-LAST:event_jButton_limparActionPerformed

    private void jTextField_descricaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_descricaoActionPerformed
        jButton_gravar.doClick();
    }//GEN-LAST:event_jTextField_descricaoActionPerformed

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new FeriadosFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_deletar;
    private javax.swing.JButton jButton_gravar;
    private javax.swing.JButton jButton_limpar;
    private javax.swing.JButton jButton_pesquisar;
    private com.toedter.calendar.JDateChooser jDateChooser_data;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabeldata;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField_descricao;
    // End of variables declaration//GEN-END:variables

    private void preencher_jtable(String tipo, String texto) {

        FeriadoDAO dao_lista = new FeriadoDAO();
        Feriado feriado_lista = new Feriado();

        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        modelo.setNumRows(0);

        DefaultTableCellRenderer centralizado = new DefaultTableCellRenderer();
        centralizado.setHorizontalAlignment(SwingConstants.CENTER);

        JTableHeader titulos = jTable1.getTableHeader();

        titulos.setFont(new Font("Dialog", Font.BOLD, 10));

        jTable1.getColumnModel().getColumn(1).setCellRenderer(centralizado);
        jTable1.getColumnModel().getColumn(2).setCellRenderer(centralizado);

        jTable1.getColumnModel().getColumn(0).setMaxWidth(0);
        jTable1.getColumnModel().getColumn(0).setMinWidth(0);
        jTable1.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(0);

        jTable1.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(0);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(150);
        try {

            if (tipo != null && tipo.equals("descricao")) {
                lista = dao_lista.buscaDescricao(texto);
            } else {
                lista = dao_lista.getLista();
            }

            int tamanho_lista = lista.size();
            String dados = "";
            if (!lista.isEmpty()) {

                for (int i = 0; i < tamanho_lista; i++) {
                    feriado_lista = lista.get(i);

                    modelo.addRow(new Object[]{
                                feriado_lista.getId(),
                                data.format(feriado_lista.getData()),
                                feriado_lista.getDescricao(),});
                }

            } else {
                modelo.addRow(new String[]{" ", ""});
                modelo.addRow(new String[]{" ", ""});
                int linha = jTable1.getRowCount();
                jTable1.setValueAt("Nenhum registro ", linha - 2, 2);
                jTable1.setValueAt("encontrado ! ", linha - 1, 2);
            }
        } catch (Exception erro) {
            JOptionPane.showMessageDialog(null, "erro ao listar Jtable" + erro);
            erro.printStackTrace();
        }

    }


    public boolean duplicado() {

        int linha = jTable1.getSelectedRow();

        boolean bdata = false, bdescricao = false, result = false;
        
      String  data_tb  = "",  descricao_tb  = "",
              data_txt = "",  descricao_txt = "";

        if (linha >=0 )
        {
        
           if( jTable1.getValueAt(linha, 1)!= null ) 
                data_tb = (String) jTable1.getValueAt(linha, 1);
           
           if ( jTable1.getValueAt(linha, 2) != null )
                descricao_tb = (String) jTable1.getValueAt(linha, 2);
           
           if ( jDateChooser_data.getDate() != null )
                data_txt = data.format(jDateChooser_data.getDate());
           
           if ( !jTextField_descricao.getText().trim().equals("") )
                descricao_txt = jTextField_descricao.getText().trim();

        if (data_tb.equals(data_txt)) {
            bdata = true;
        }
        
        if (descricao_tb.equals(descricao_txt)) {
            bdescricao = true;
        }
        if (bdata && bdescricao ) {
            result = true;
        }
                    
        }
        return result;
    }
    
}
